home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8723 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  74 lines

  1. Path: news.lpr.carel.fi!usenet
  2. From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: revised code of calling a function twice from printf
  5. Date: Tue, 05 Mar 1996 13:36:36 +0200
  6. Organization: Carelcomp Forest
  7. Message-ID: <313C2744.7FE7@cmt.lpr.mail.carel.fi>
  8. References: <4hfs54$k4e@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: renoir.cclahti.carel.fi
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (WinNT; I)
  14.  
  15. Razine wrote:
  16. > Here is the actual code , modified with everyone's suggestions.  However
  17. > there is still a bug in here somewhere.  Can anyone please explain what is
  18. > wrong with this.
  19. > It returns
  20. > [1] NONE       [2] NE
  21. > I would like it to return
  22. > [1] NONE       [2] Asprin
  23. > Thank you very much for your help.  it is greatly appreciated.
  24. > #include <stdio.h>
  25. > #include <string.h>
  26. > char *display_drug_type(int drug_index);
  27. > int drug_inventory[5]={0,1,0,0,0};
  28. > int main() {
  29. >     printf("[1] %s             [2] %s
  30. > \n",display_drug_type(0),display_drug_type(1));
  31. > return 0;
  32. >         }
  33. > char *display_drug_type(int drug_index) {
  34. >    char drug_type[81]="\0";
  35. >    switch(drug_inventory[drug_index]) {
  36. >      case 0 : strcpy(drug_type,"NONE"); break;
  37. >      case 1 : strcpy(drug_type,"Asprin"); break;
  38. >      default : printf("Error in Display_drug_inventory");
  39. >                                                 }
  40. >    return drug_type;
  41. > }
  42.  
  43. In the printf, you call the same function twice. The order in which it gets called is 
  44. undetermined, thus the contents of drug_type will be undetermined. Why not rewrite 
  45. display_drug_type as:
  46.  
  47.     char    *display_drug_type(int drug_index)
  48.     {
  49.         switch (drug_inventory[drug_index]) {
  50.             case 0: return "NONE";
  51.             case 1: return "Asprin";
  52.         }
  53.         return "Invalid";
  54.     }
  55.  
  56. Later,
  57.  AriL
  58. -- 
  59. All my opinions are mine and mine alone.
  60.